package com.work.farm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.work.farm.dao.FarmDao;
import com.work.farm.pojo.TCustFarmEntity;
import com.work.farm.service.FarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class FarmServiceImpl implements FarmService {

    @Autowired
    private FarmDao farmDao;

    //查询所有
    @Override
    public List find(Integer id, String name, int page, int size) {
        return farmDao.selectAll();
    }

    //添加农场片区
    @Override
    public void addFarm(TCustFarmEntity tCustFarmEntity) {
        //设置农场片区状态为可用
        tCustFarmEntity.setStatus("1");
        System.out.println(tCustFarmEntity.toString());
        farmDao.add(tCustFarmEntity);
    }

    //修改农场片区的状态信息
    @Override
    public void updateFarm(TCustFarmEntity tCustFarmEntity) {
        //修改状态
        farmDao.updateByPrimaryKeySelective(tCustFarmEntity);
    }

    //分页搜索条件查询农场,包括根据id进行查询
    @Override
    public Page<TCustFarmEntity> findByPage(Integer pageNum, Integer pageSize, Map searchMap) {
        PageHelper.startPage(pageNum, pageSize);
        Example example = createExample(searchMap);
        return (Page<TCustFarmEntity>) farmDao.selectByExample(example);
    }

    @Override
    public TCustFarmEntity findById(Integer id) {
        return farmDao.selectByPrimaryKey(id);
    }

    //构建一个私有的查询条件对象
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(TCustFarmEntity.class);
        Example.Criteria criteria = example.createCriteria();
        //判断是否是根据id进行查询
        //判断需要的查询条件是否存在
        if (searchMap != null) {
            //农场片区编号
            if (searchMap.get("code") != null && !"".equals(searchMap.get("code"))) {
                criteria.andEqualTo("code", searchMap.get("code"));
            }
            //大田名字
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
        }
        return example;
    }


}
